import { useState } from 'react';
import type { ActionType, ProColumns, RequestData } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import type { TableProps } from 'antd';
import { Button, Modal } from 'antd';
import { handleRemove } from '@/utils/handler';
import type { SearchConfig } from '@ant-design/pro-table/lib/components/Form/FormRender';
import styles from './index.less';

function BasicTable<T>(props: {
  actionRef?: React.MutableRefObject<ActionType | undefined>;
  rowKey?: string;
  title?: React.ReactNode;
  columns: ProColumns<T>[];
  polling?: number | ((dataSource: T[]) => number);
  search?: false | SearchConfig | undefined;
  rowSelection?:
  | (TableProps<T>['rowSelection'] & {
    alwaysShowAlert?: boolean;
  })
  | false;
  params?: AnyFields;
  postData?: (data: T[]) => AnyFields[];
  listAction: (
    params: PageParams & AnyFields,
    options?: AnyFields | undefined,
  ) => Promise<RequestData<T>>;
  removeAction?: (ids: string) => Promise<Record<string, any>>;
  onAdd?: () => void;
  onReload?: () => void;
}) {
  const [selectedRows, setSelectedRows] = useState<T[]>([]);

  const {
    actionRef,
    rowKey = 'id',
    title,
    columns,
    polling,
    search = { labelWidth: 'auto' },
    rowSelection = {
      selectedRowKeys: selectedRows.map((item) => item[rowKey]),
      onChange: (_, rows) => {
        setSelectedRows(rows);
      },
    },
    params = {},
    postData,
    listAction,
    removeAction,
    onAdd,
    onReload,
  } = props;

  return (
    <ProTable<T, PageParams>
      headerTitle={title}
      actionRef={actionRef}
      rowKey={rowKey}
      search={search}
      polling={polling}
      toolBarRender={() => [
        onAdd && (
          <Button type="primary" key="primary" onClick={() => onAdd()}>
            <PlusOutlined /> 新增
          </Button>
        ),
        removeAction && (
          <Button
            danger
            onClick={async () => {
              if (selectedRows.length === 0) return;
              Modal.confirm({
                title: '删除',
                icon: <QuestionCircleOutlined className={styles.removeQuestionIcon} />,
                content: '确定删除选中项？',
                okButtonProps: { danger: true },
                okText: '确认',
                cancelText: '取消',
                onOk: async () => {
                  await handleRemove(
                    selectedRows.map((row) => row[rowKey]).join(','),
                    removeAction,
                  );
                  setSelectedRows([]);
                  if (onReload) onReload();
                },
              });
            }}
          >
            批量删除
          </Button>
        ),
      ]}
      request={listAction}
      postData={postData}
      params={params}
      columns={columns}
      rowSelection={rowSelection}
    />
  );
}

export default BasicTable;
